package com.abso.sunlight.api;

import org.dom4j.Element;

/**
 * A set of utility methods able to handle data returned from the Sunlight Labs API.
 */
public class SunlightDataUtils {

    /** Private constructor (don't instantiate). */
    private SunlightDataUtils() {
    }

    /**
     * Extracts a string value from a XML element.
     * 
     * @param elem
     *            the element whose string value must be returned.
     * @param path
     *            the XPath to be used to locate the value.
     * @return the extracted string value.
     */
    public static String getString(Element elem, String path) {
        return elem.valueOf(path);
    }

    /**
     * Extracts a boolean value from a XML element.
     * 
     * @param elem
     *            the element whose boolean value must be returned.
     * @param path
     *            the XPath to be used to locate the value.
     * @return the extracted boolean value.
     * @throws SunlightException
     *             if an error occurred extracting the value.
     */
    public static boolean getBoolean(Element elem, String path) throws SunlightException {
        String value = elem.valueOf(path);
        if (value.equals("1")) {
            return true;
        } else if (value.equals("0")) {
            return false;
        } else {
            throw new SunlightException("Invalid boolean value: expecting either '1' or '0' but got '" + value + "'");
        }
    }

    /**
     * Extracts an integer value from a XML element.
     * 
     * @param elem
     *            the element whose integer value must be returned.
     * @param path
     *            the XPath to be used to locate the value.
     * @return the extracted integer value.
     * @throws SunlightException
     *             if an error occurred extracting the value.
     */
    public static int getInt(Element elem, String path) throws SunlightException {
        try {
            return Integer.parseInt(elem.valueOf(path));
        } catch (NumberFormatException e) {
            throw new SunlightException(e);
        }
    }

    /**
     * Extracts a double value from a XML element.
     * 
     * @param elem
     *            the element whose double value must be returned.
     * @param path
     *            the XPath to be used to locate the value.
     * @return the extracted double value.
     * @throws SunlightException
     *             if an error occurred extracting the value.
     */
    public static double getDouble(Element elem, String path) throws SunlightException {
        try {
            return Double.parseDouble(elem.valueOf(path));
        } catch (NumberFormatException e) {
            throw new SunlightException(e);
        }
    }

}
